package luaengine

/**
 * Lua运行时池
 */

import (
	"errors"
	"time"

	lua "github.com/yuin/gopher-lua"
)

var statePool chan *lua.LState

//
func InitLStatePool(poolSize int) {
	statePool = make(chan *lua.LState, poolSize)
	for i := 0; i < poolSize; i++ {
		statePool <- lua.NewState()
	}
}

//GetLState
func GetLState() (*lua.LState, error) {
	select {
	case <-time.After(2 * time.Second):
		return nil, errors.New("获取state超时")
	case state := <-statePool:
		return state, nil
	}
}

//PutLState
func PutLState(state *lua.LState) {
	statePool <- state
}

//销毁处理
func LStatePoolDestory() {
	for {
		state, err := GetLState()
		if err != nil {
			break
		}
		state.Close()
	}
}
